package com.taptech.doufu.ui.activity;

import android.content.Intent;
import android.os.Bundle;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity;
import com.taptech.doufu.util.CacheUtil;
import com.taptech.doufu.R;
import com.taptech.doufu.ui.adapter.MoreAlbumsViewAdapter;
import com.taptech.doufu.bean.AlbumsBean;
import com.taptech.doufu.bean.IconTypeBeans;
import com.taptech.doufu.constant.RecycleViewLoadType;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.ui.view.drawcircle.MyRecyclerView;
import com.taptech.doufu.ui.view.drawcircle.MySwipeRefreshLayout;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.services.HomeMainServices;
import com.taptech.doufu.util.DiaobaoUtil;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.util.URLParseUtils;
import com.taptech.doufu.net.httputils.HttpResponseObject;
import com.taptech.doufu.ui.view.WaitDialog;
import com.taptech.doufu.ui.viewholder.HomeSubjectItemViewHolder;
import com.taptech.doufu.ui.viewholder.NewHomeSubjectItemViewHolder;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 专题
 */
public class MoreAlbumsActivity extends DiaobaoBaseActivity implements HttpResponseListener
{

    //part: <1|2|4|5> , 热门｜小说文评｜绘画｜排行版*/
    // 三个方形
    public static final int HOT_ALBMUS = 1;
    // 二个矩形
    public static final int NOVELSWEEP_ALBMUS = 2;
    public static final int DRAW_ALBMUS = 4;
    public static final int RANK_ALBMUS = 5;
    public static final int NOVEL_ALBMUS = 6;
    public static final int COMMON_ALBMUS = 7;
    //推荐小说更多活动专题
    public static final String NOVEL_MORE_ALBMUS = "http://api.doufu.la/index.php/albums/items?id=70";
    private MyRecyclerView recyclerView;
    private MoreAlbumsViewAdapter adapter;
    // 用于下拉刷新
    private MySwipeRefreshLayout swipeRefreshLayout;
    WaitDialog mWaitDialog;
    private List<AlbumsBean> mDataList;
    private String last = "";
    private boolean hasMoreContent = true;
    private int page = 0;
    public static int type;
    // 在绘画和小说首页才会有
    private String url;
    private String title;
    private TextView title_text;
    private boolean needChangeData = false;
    private String tempSting;
    private TextView personal_note_more;
    private String helpUrl;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {

        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_more_albums_layout);
        initWaitWindow();
        initTypeData();
        initView();
        loadAlbums();

    }

    @Override
    public void handleResponse(int handleType, final HttpResponseObject response)
    {
        // TODO Auto-generated method stub
        if (mWaitDialog != null && mWaitDialog.isShowing())
        {
            mWaitDialog.dismiss();
        }
        //再次开启下拉刷新
        swipeRefreshLayout.isRefreshing();
        //隐藏顶部视图
        // adapter.setHeadViewVisible(View.GONE);

        if (response == null)
        {
            UIUtil.toastMessage(this, Constant.loadingFail);
            return;
        }
        switch (handleType)
        {
            case HomeMainServices.HANDLE_TYPE_LOAD_MORE_ALBUMS:
                if (hasMoreContent)
                {
                    JSONObject data = (JSONObject) response.getData();
                    try
                    {
                        List<AlbumsBean> dataList = DiaobaoUtil.json2list(AlbumsBean.class, data.getJSONArray("albums"));
                        if (dataList == null || dataList.size() <= 0)
                        {
                            //数据为空
                            hasMoreContent = false;
                            recyclerView.setLoadMoreEnable(false);
                        } else
                        {
                            //正常加载数据
                            hasMoreContent = true;
                            recyclerView.setLoadMoreEnable(true);
                            if (page == 0)
                            {
                                mDataList.clear();
                            }
                            mDataList.addAll(dataList);
                            adapter.notifyDataSetChanged();
                        }
                        page = page + 1;
                    } catch (JSONException e)
                    {
                        e.printStackTrace();
                    }
                }
                break;
            case HomeMainServices.HANDLE_TYPE_LOAD_ALBUMS:
                if (hasMoreContent)
                {
                    JSONObject data = (JSONObject) response.getData();
                    try
                    {
                        List<AlbumsBean> dataList = new ArrayList<AlbumsBean>();
                        if (needChangeData)
                        {
                            if ((last == null) || (last.equals("")))
                            {
                                try
                                {
                                    tempSting= URLParseUtils.parseA(url);
                                    if (response.getStatus() == Constant.STATUS_SUCCESS)
                                    {
                                        new Thread(new Runnable()
                                        {
                                            @Override
                                            public void run()
                                            {
                                                CacheUtil.saveJsonDataToCache(response.getData().toString(), new File(Constant.AppDir.FILE_CACHE_DATA_MAIN + tempSting));
                                            }
                                        }).start();
                                    } else
                                    {
                                        UIUtil.toastMessage(MoreAlbumsActivity.this, DiaobaoUtil.getErrorTips(response));
                                        data = CacheUtil.readJsonDataFromCache(new File(Constant.AppDir.FILE_CACHE_DATA_MAIN + tempSting));
                                    }
                                } catch (Exception e)
                                {
                                    e.printStackTrace();
                                }
                            }

                            List<IconTypeBeans> iconBeans = com.alibaba.fastjson.JSONArray.parseArray(data.getJSONArray("list").toString(), IconTypeBeans.class);
                            if ((iconBeans != null) && (iconBeans.size() > 0))
                            {
                                for (int i = 0; i < iconBeans.size(); i++)
                                {
                                    AlbumsBean tempAlbumsBean = new AlbumsBean();
                                    tempAlbumsBean.setName(iconBeans.get(i).getTitle());
                                    tempAlbumsBean.setCover(iconBeans.get(i).getImgUrl());
                                    tempAlbumsBean.setIcon(iconBeans.get(i).getImgUrl());
                                    if (iconBeans.get(i).getUrl().contains("?"))
                                    {
                                        tempAlbumsBean.setUrl(iconBeans.get(i).getUrl());
                                    } else
                                    {
                                        tempAlbumsBean.setUrl(iconBeans.get(i).getUrl() + "?");
                                    }
                                    dataList.add(tempAlbumsBean);
                                }
                            }
                        } else
                        {
                            if ((last == null) || (last.equals("")))
                            {
                                try
                                {
                                    tempSting= URLParseUtils.parseA(url);
                                    if (response.getStatus() == Constant.STATUS_SUCCESS)
                                    {
                                        new Thread(new Runnable()
                                        {
                                            @Override
                                            public void run()
                                            {
                                                CacheUtil.saveJsonDataToCache(response.getData().toString(), new File(Constant.AppDir.FILE_CACHE_DATA_MAIN + tempSting));
                                            }
                                        }).start();
                                    } else
                                    {
                                        UIUtil.toastMessage(MoreAlbumsActivity.this, DiaobaoUtil.getErrorTips(response));
                                        data = CacheUtil.readJsonDataFromCache(new File(Constant.AppDir.FILE_CACHE_DATA_MAIN + tempSting));
                                    }
                                } catch (Exception e)
                                {
                                    e.printStackTrace();
                                }
                            }
                            dataList = DiaobaoUtil.json2list(AlbumsBean.class, data.getJSONArray("items"));
                        }

                        if (last.equals(""))
                        {
                            //正常加载数据
                            hasMoreContent = true;
                            recyclerView.setLoadMoreEnable(true);
                            mDataList.clear();
                            mDataList.addAll(dataList);
                            adapter.notifyDataSetChanged();
                        } else if (!last.equals(data.getString("last")))
                        {
                            hasMoreContent = true;
                            recyclerView.setLoadMoreEnable(true);
                            mDataList.addAll(dataList);
                            adapter.notifyDataSetChanged();
                        } else
                        {
                            hasMoreContent = false;
                            recyclerView.setLoadMoreEnable(false);

                        }
                        last = data.getString("last");

                    } catch (JSONException e)
                    {
                        e.printStackTrace();
                    }
                }
                break;
        }

    }

    private void initTypeData()
    {
        needChangeData = getIntent().getBooleanExtra(RecycleViewLoadType.recycleNeedChangeData, false);
        type = getIntent().getIntExtra(Constant.TYPE, 1);
        url = getIntent().getStringExtra(Constant.URL);
        title = getIntent().getStringExtra(Constant.TITLE);
        helpUrl = getIntent().getStringExtra(Constant.HELP_URL);
        mDataList = new ArrayList<AlbumsBean>();
    }

    RecyclerView.LayoutManager layoutManager;

    private void initView()
    {
        title_text = (TextView) findViewById(R.id.personal_note_title_text);
        personal_note_more = (TextView) findViewById(R.id.personal_note_more);
        initHelpBtn();
        swipeRefreshLayout = (MySwipeRefreshLayout) findViewById(R.id.swipe_container);
        recyclerView = (MyRecyclerView) findViewById(R.id.albmus_gridview);
        layoutManager = new GridLayoutManager(this, type == HOT_ALBMUS ? 2 : 3);
        recyclerView.setLayoutManager(layoutManager);
        initTitle();
        adapter = new MoreAlbumsViewAdapter(this, mDataList);
        //adapter.setHeaderView(R.layout.recyclerview_pull_headview);

        recyclerView.setAdapter(adapter);
        recyclerView.setOnScrollToBottomListener(new MyRecyclerView.OnScrollToBottomListener()
        {
            @Override
            public void loadMore()
            {
                loadMoreAlbmus();
            }
        });
        recyclerView.setOnScrollToTopListener(new MyRecyclerView.OnScrollToTopListener()
        {
            @Override
            public void refresh()
            {
                if (!adapter.isHeadViewVisible())
                    swipeRefreshLayout.setEnabled(false);
            }

            @Override
            public void notAtTopInScrollView(int offsetY, int directionY)
            {
                swipeRefreshLayout.setEnabled(false);
            }
        });
        swipeRefreshLayout.setEnabled(false);
        //swipeRefreshLayout.setmProgressDrawable(getResources().getDrawable(R.drawable.ic_launcher));
        //刷新动画
        swipeRefreshLayout.setSize(0);

    }

    private void initHelpBtn() {
        if (!TextUtils.isEmpty(helpUrl)) {
            personal_note_more.setText("介绍规则");
            personal_note_more.setVisibility(View.VISIBLE);
            personal_note_more.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(MoreAlbumsActivity.this, BrowseActivity.class);
                    intent.putExtra(Constant.URL, helpUrl);
                    intent.putExtra(Constant.TITLE, "介绍规则");
                    MoreAlbumsActivity.this.startActivity(intent);
                }
            });
        }else{
            personal_note_more.setVisibility(View.INVISIBLE);
        }
    }

    private void initTitle()
    {


        if (title != null)
        {
            title_text.setText(title);
        } else
        {
            switch (type)
            {
                case HOT_ALBMUS:
                    title_text.setText(NewHomeSubjectItemViewHolder.SUBJECT_TYPE_POPULAR);
                    break;
                case NOVELSWEEP_ALBMUS:
                    title_text.setText(HomeSubjectItemViewHolder.SUBJECT_TYPE_SWEEP);
                    break;
                case DRAW_ALBMUS:
                    title_text.setText(HomeSubjectItemViewHolder.SUBJECT_TYPE_DRAW);
                    break;
                case RANK_ALBMUS:
                    title_text.setText(HomeSubjectItemViewHolder.SUBJECT_TYPE_RANK);
                    break;
                case NOVEL_ALBMUS:
                    title_text.setText(HomeSubjectItemViewHolder.SUBJECT_NOVEL_ACTIVITY);
                case COMMON_ALBMUS:
                    title_text.setText(NewHomeSubjectItemViewHolder.SUBJECT_TYPE_COMMON);
                    break;
            }
        }
    }

    private synchronized void loadAlbums()
    {
        if (mDataList != null)
        {
            page = 0;
            hasMoreContent = true;

            if (url != null)
            {
                HomeMainServices.getInstance().loadAlbumsList(this, url, last);
            } else
            {
                HomeMainServices.getInstance().loadMoreAlbums(type + "", Constant.PAGE_SIZE_12, page, this);
            }
        }
    }

    private synchronized void loadMoreAlbmus()
    {
        if (hasMoreContent)
        {


            if (url != null)
            {
                HomeMainServices.getInstance().loadAlbumsList(this, url, last);
            } else
            {

                HomeMainServices.getInstance().loadMoreAlbums(type + "", Constant.PAGE_SIZE_12, page, this);
            }
        }
    }

    private void initWaitWindow()
    {
        mWaitDialog = new WaitDialog(this, R.style.loadNovelDialog, "");
        mWaitDialog.setCanceledOnTouchOutside(false);
        mWaitDialog.show();
    }

    public void back(View v)
    {
        finish();
    }
}
